package com.zzy.threadtest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolCompletionService {

    int corePoolSize = 5;//核心线程数
    int maxPoolSize = 100;//最大线程数
    long keepAliveTime = 120L;//线程最大活动时间
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    ExecutorService executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, handler);

    public void test(int threadCount) {
        try {
            CompletionService<String> service = new ExecutorCompletionService<>(executor);
            final List<Callable<String>> tasks = new ArrayList<>();

            for (int i = 1; i <= threadCount; i++) {
                int index = i;
                tasks.add(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return "call-->" + index;
                    }
                });
            }
            System.out.println("==========================================");
            tasks.forEach(service::submit);
            for (int i = 0; i < tasks.size(); i++) {
                Object o = service.take().get();

                System.out.println("执行完毕返回值为："+o);
                System.out.println("----------------------------------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //executor.shutdown();//关闭线程池
    }

    public static void main(String[] args) {
        (new ThreadPoolCompletionService()).test(5);
    }

}
